// index.ts

import { UserApi } from "../../api/user.api"

// 获取应用实例
const app = getApp<IAppOption>()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  onLoad() {
    // console.log("触发了加载钩子");
    // wx.redirectTo({
    //   url: '/pages/home/home'
    // })
  },
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },

  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs',
    })
  },

  onInputChange(e: any) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  /**注册按钮点击事件 */
  handleSignup() {
    if (!this.data.hasUserInfo) return
    wx.login({
      success: async (res) => {

        if (res.code) {
          wx.showLoading({
            title: "加载中"
          })
          console.log(this.data.userInfo.avatarUrl);

          let filenameArr = this.data.userInfo.avatarUrl.split('/')
          // 获取文件管理器
          const fs = wx.getFileSystemManager();
          try {
            // 读取文件并转为 Base64
            const base64Data = fs.readFileSync(this.data.userInfo.avatarUrl, 'base64');

            let signupRes = await UserApi.signup(filenameArr[filenameArr.length - 1], base64Data as string, this.data.userInfo.nickName, res.code)
            wx.hideLoading()
            if (signupRes.success) {
              wx.setStorageSync("token", signupRes.data.token)
              wx.reLaunch({
                url: "/pages/home/home"
              })
              wx.showToast({
                title: "注册成功"
              })
            } else {
              wx.showToast({
                icon: "error",
                title: signupRes.msg
              })
            }
          } catch (error) {
            console.error('读取文件失败', error);
          }
        } else {
          console.log('登录失败！', res.errMsg);
        }
      }
    });



  }

})
